<?php
namespace Crm\Domain;

use Crm\Common\MetaData as MetaData;

class Mall
{
    /**
     * pdo连接。
     *
     * @var object
     * @access pdo
     */
    public $pdo;

    public $metaData;
    public $baseCode;
    public $city_code;
    public $provinceCode;

    public function __construct()
    {
        $this->pdo = \PhalApi\DI()->pdo;
        $this->baseCode = (object)\PhalApi\DI()->config->get('basecode');
        $this->province_code = \PhalApi\DI()->config->get('app.provinceCode');//省
        $this->city_code = \PhalApi\DI()->config->get('app.cityCode');//城市

        $this->metaData = new MetaData();
    }

    /* 商城配置 */
    public function config($mall_id){
        $sql = "select a.*,b.app_name from mk_mall as a left JOIN wx_wechat as b on a.wechat_id=b.id where a.flag=1 and a.id=" . $mall_id;
        //初始数据
        $Info = $this->pdo->getRow($sql);
        $Info['create_date_val'] = date('Y-m-d H:i',$Info['create_date']);

        $arr=explode("\n",$Info['service']);
        foreach ($arr as $value){
            $Info['service_list'][] =$value;
        }

        //todo 后台设置积分单位、每日积分次数
        if($Info['setting']==''){
            //配置参数
            $Info['setting']['score_unit'] ='积分';//积分单位
            //每日积分配置
            $Info['setting']['dayReadTimes']  = 3;   //每日获取阅读积分次数
            $Info['setting']['dayShareTimes'] = 3;  //每日获取分享积分次数
        }else {
            $Info['setting'] = unserialize($Info['setting']);
            $Info['setting']['score_unit'] = '积分';//积分单位
            //每日积分配置
            $Info['setting']['dayReadTimes']  = 3;   //每日获取阅读积分次数
            $Info['setting']['dayShareTimes'] = 3;  //每日获取分享积分次数
        }
        //index_img
        $Info['index_img_s'] = str_replace('.','_s.',$Info['index_img']);
        $Info['index_img_m'] = str_replace('.','_m.',$Info['index_img']);
        //logo_img
        $Info['logo_img_s'] = str_replace('.','_s.',$Info['logo_img']);
        $Info['logo_img_m'] = str_replace('.','_m.',$Info['logo_img']);
        //logo_img
        $Info['bg_img_s'] = str_replace('.','_s.',$Info['bg_img']);
        $Info['bg_img_m'] = str_replace('.','_m.',$Info['bg_img']);
        return $Info;
    }

    /* 获取配置项 */
    public function setting($mall_id,$data,$type="list"){
        $where = 'a.flag=1 AND a.mall_id='.$mall_id.' ';
        if(isset($data['code']) && !empty($data['code'])){
            $where .= " AND a.code = ".$data['code'];
        }
        if(isset($data['parent_code']) && !empty($data['parent_code'])){
            $where .= " AND a.parent_code = ".$data['parent_code'];
        }
        if(isset($data['alias']) && !empty($data['alias'])){
            $_alias = explode(',',$data['alias']);
            if(count($_alias)>1) {
                $in = '';
                foreach ($_alias as $as) {
                    $in .= "'" . $as . "',";
                }
                $in=substr($in,0,-1);
                $where .= " AND a.alias in (".$in.")";
            }else{
                $where .= " AND a.alias = '".$data['alias']."'";
            }
        }

        $sql = "select a.* from mk_mall_setting as a  where ".$where;
        $setting = $this->pdo->getAll($sql);
        foreach ($setting as $key=>$set){
            if($set['img_url']!=''){
                $setting[$key]['img_url_s'] = str_replace('.','_s.',$set['img_url']);
                $setting[$key]['img_url_m'] = str_replace('.','_m.',$set['img_url']);
            }
            switch ($set['wap']){
                case 'switchTab':
                    $setting[$key]['bindTap'] = 'switchTab';
                    break;
                case 'webview':
                    $setting[$key]['bindTap'] = 'webView';
                    break;
            }
            //处理文本-rule
            $arr=explode("\n",$set['rule']);
            $str='';
            $pstr='';
            foreach ($arr as $value){
                $str .=$value.'<br>';
                $pstr .='<p>'.$value.'</p>';
            }
            $setting[$key]['rule'] = $str;
            $setting[$key]['prule'] = $pstr;

            //统计配置的对象为一个值还是多个值
            if(isset($settingNum[$set['alias']])) {
                $settingNum[$set['alias']] = $settingNum[$set['alias']]+1;
            }else{
                $settingNum[$set['alias']] =1;
            }
        }
        if($type=='keylist'){
            //键名为alias
            foreach ($setting as $item){
                if($settingNum[$item['alias']]>1){
                    $_settings[$item['alias']][] = $item;
                }else{
                    $_settings[$item['alias']] = $item;
                }
            }
            return $_settings;
        }elseif($type=='one'){
            return $setting[0];
        }else{
            return $setting;
        }
    }

    /* 商城礼品列表 */
    public function awardList($mall_id,$data){
        $order = isset($data['order']) ? $data['order'] : 'sort desc';
        $pageSize = isset($data['pageSize']) ? $data['pageSize'] : 30;
        $offset = 0;
        $subPages=5;//每次显示的页数
        $currentPage = isset($data['page']) ? (int)$data['page'] : 0;
        if($currentPage>0) $offset=($currentPage-1)*$pageSize;

        $where = 'a.flag=1 AND a.is_putaway=1 AND a.mall_id='.$mall_id.' ';
        if(isset($data['key']) && !empty($data['key'])){
            $where .= " AND a.name like '%".$data['code']."%'";
        }

        if(isset($data['type']) && !empty($data['type'])) {
            $where .= " AND a.type = " . $data['type'];
        }

        $order = " order by $order";
        $limit = " limit $offset,$pageSize";
        //获取商品
        $sql = "select * from mk_mall_award as a where ".$where.$order.$limit;
        $awards = $this->pdo->getAll($sql);
        foreach ($awards as $key=>$item){
            $awards[$key]['type_val'] = $this->type_option[$item['type']];
            $awards[$key]['unit_val'] = $this->unit_option[$item['unit']];
            $awards[$key]['img_url_s'] = str_replace('.','_s.',$item['img_url']);
            $awards[$key]['img_url_m'] = str_replace('.','_m.',$item['img_url']);
        }
        return $awards;
    }

    /* 礼品详情 */
    public function awardDetail($award_id){
        $sql = "select * from mk_mall_award as a where id={$award_id}";
        $rlt = $this->pdo->getRow($sql);
        $rlt['type_val'] = $this->type_option[$rlt['type']];
        $rlt['unit_val'] = $this->unit_option[$rlt['unit']];
        $rlt['img_url_s'] = str_replace('.','_s.',$rlt['img_url']);
        $rlt['img_url_m'] = str_replace('.','_m.',$rlt['img_url']);
        //获取相册
        $rlt['pics'] = $this->awardPhoto($award_id);
        return $rlt;
    }

    /* 礼品相册 */
    public function awardPhoto($award_id){
        $sql = "select name,url,code,title from sys_attach as a where flag=1 and action='mall_award' and action_id={$award_id} ORDER BY sort desc";
        $rlt = $this->pdo->getAll($sql);
        foreach ($rlt as $key=>$item) {
            $rlt[$key]['url_s'] = str_replace('.', '_s.', $item['url']);
            $rlt[$key]['url_m'] = str_replace('.', '_m.', $item['url']);
        }
        //获取相册
        return $rlt;
    }

    /* 礼品兑换 */
    public function awardConvert($user_id,$award_id=0,$mall_id=0,$user_type=9){
        if($user_id!='' && $award_id!=0 && $mall_id!=0) {
            $info = $this->awardDetail($award_id);
            if($info['stock_num']<1){
                $resutl = array('status' => '200', 'msg' => '很抱歉,该商品已经兑换完了,您可以兑换其他商品!');
                return $resutl;
            }
            $Score = new Score();
            $score = $Score->countUserScore($user_id);
            //user_type=8为业主,兑换积分8折
            if($user_type==8)$info['score'] = round($info['score']*0.8);
            if($score['surplus']>=$info['score']) {
                $data = array(
                    'create_date' => time(),
                    'create_uid' => $user_id,
                    'award_id'=>$award_id,
                    'mall_id'=>$mall_id
                );
                $user_award_id = $this->pdo->add($data, 'wx_user_award');
                //记录兑奖积分
                $data = array(
                    'create_date' => time(),
                    'create_uid' => $user_id,
                    'flag' => 1,
                    'mall_id' => $mall_id,//只要后期需要统计项目所有积分时才有用
                    'name' => $info['name'],
                    'score' => $info['score'],
                    'type' => $info['type'],
                    'category' => 2,
                    'desc' => $info['desc'],
                    'action' => 'wx_user_award',
                    'action_id' => $user_award_id
                );
                $this->pdo->add($data, 'wx_user_score');

                //跟新奖品库存
                $sql = "update mk_mall_award set stock_num=stock_num-1 where id={$award_id}";
                $this->pdo->doSql($sql);

                if ($user_award_id) {
                    $resutl = array('status' => '200', 'msg' => '恭喜您,兑换商品成功!');
                } else {
                    $resutl = array('status' => '201', 'msg' => '很抱歉,您没有获得积分');
                }
            }else{
                $resutl = array('restatust' => '202', 'msg' => '很抱歉,您的积分不够!');
            }
        }else{
            $resutl = array('status' => '400', 'msg' => '操作失败！');
        }
        return $resutl;
    }
}

